package com.hw.dagl.controller;


import static com.hw.utils.DESCrypt.encrypt;
import static com.hw.utils.DESCrypt.toHexString;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.tools.zip.ZipEntry;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hw.dagl.model.Dagl_T_Audit;
import com.hw.dagl.model.Driver_audit;
import com.hw.dagl.model.Sys_Role;
import com.hw.dagl.model.Sys_User;
import com.hw.dagl.model.Vehicle;
import com.hw.dagl.service.IAuditService;
import com.hw.dagl.service.YxxxglService;
import com.hw.dagl.service.impl.FrmCodeServiceImpl;
import com.hw.dagl.service.impl.YxxxglServiceImpl;
import com.hw.dao.utils.ControllerUtil;
import com.hw.dao.utils.GcPage;
import com.hw.dao.utils.Page;
import com.hw.dao.utils.PageUtil;
import com.hw.interceptor.SystemLog;

import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author Administrator
 * 影像信息
 */
@Controller
public class YxxxglController extends BaseController{
	@Resource
	private YxxxglService YxxxglServiceImpl;
	
	@Autowired
    private IAuditService auditService;
	/**
	 * 跳转到机动车列表页面（审核后的）
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String jdcList(HttpServletResponse response){
		return "yxgl/jdcList";
	}
	/**
	 * 跳转到机动车档案移交列表页面
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String dayjList(HttpServletResponse response){
		return "dayj/dayjList";
	}
	/**
	 * 跳转到驾驶证列表页面（审核后的）
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String jszList(HttpServletResponse response){
		return "yxgl/jszList";
	}

	/**
	 * 分页显示驾驶证信息
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void findJszxxPage(HttpServletRequest request, HttpServletResponse response,
							  Page<Driver_audit> pages, Driver_audit info, String startTime, String endTime){
		Page<Driver_audit> list = YxxxglServiceImpl.findJszByPage(pages, info,startTime,endTime);
		ControllerUtil.renderJson(response, list, "encoding:UTF-8","no-cache:false");
	}



	/**
	 * 分页显示影像申请下载列表
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void findYxsqxzPage(HttpServletRequest request, HttpServletResponse response,
							   Page<Vehicle> pages, Vehicle info, String startTime, String endTime){
		HttpSession session=request.getSession();
		Sys_Role sysRole=null;
		if(null!=session){
			Sys_User sysUser=(Sys_User)session.getAttribute("user");
			sysRole=(Sys_Role)request.getSession().getAttribute("role");
			String yhdh=sysUser.getYhdh();
			info.setCjr(yhdh);
		}
		
		Page<Vehicle> list = YxxxglServiceImpl.findYxsqxzxx(pages, info,startTime,endTime,sysRole);
		if(list ==null || list.getTotal()==-1)
			ControllerUtil.renderJson(response, list, "encoding:UTF-8","no-cache:false");
		else{
		List<Vehicle> vehicles=list.getRows();
	
    	char[] ch;
		for(int i=0,size=vehicles.size();i<size;i++){
			transfCodeToName(vehicles.get(i));
	    	if(vehicles.get(i).getYwlx()!=null && vehicles.get(i).getYwlx().length()>=1){
	    		StringBuffer buf=new StringBuffer();
	    		 List<Vehicle> operList=YxxxglServiceImpl.queryOpertype(vehicles.get(i).getYwlx());
	    		 ch=vehicles.get(i).getYwyy().toCharArray();
	    		 for(int j = 0;j<ch.length;j++){
	    			 for(Vehicle v : operList){
	    				 if(v.getYwyy().equals(String.valueOf(ch[j]))){
	    					 if(j==0){
	    						 buf.append(v.getYwmc());
	    					 }else{
	    						 buf.append("|"+v.getYwmc());	 
	    					 }
	    				 }
	    			 }
	    			}
	    		 vehicles.get(i).setYwmc(buf.toString());
	    	}
		}
		ControllerUtil.renderJson(response, list, "encoding:UTF-8","no-cache:false");
		}
	}

	private void transfCodeToName(Vehicle vehicle) {
	    String scqx = vehicle.getScqx();//删除权限
	    if(null == scqx){
	        vehicle.setScqx("0");
	    }
		String hpzl=vehicle.getHpzl();
		String hpzlmc=FrmCodeServiceImpl.hpzlMap.get(hpzl);//号牌种类
		vehicle.setHpzlmc(hpzlmc);
		//String csys=vehicle.getCsys();
		//String csysmc=FrmCodeServiceImpl.clysMap.get(csys);//车身颜色
		//vehicle.setCsysmc(csysmc);
	}

	/**
	 * 根据车辆记录首次查询影像审核档案详情，第一次进入详情
	 * @param request
	 * @param response
	 */
	/*@RequestMapping(method = RequestMethod.GET)
	public ModelAndView findYxsqxzByxhFirstIn(HttpServletRequest request,HttpServletResponse response,PageUtil page,
			Vehicle info,String startTime,String endTime,String xhs){
		//历史原因，这个方法暂时就这样，不动了
		ModelAndView mv = new ModelAndView("yxgl/jdcView");
		String xh=info.getXh();
		String preXh="";//上一个序号
		String currentXh="";//当前序号
		String nextXh="";//下一个序号
		if(StringUtils.isNotEmpty(xh)){
		    String[] xhArr=xh.split(",");
		    preXh=xhArr[0];
		    currentXh=xhArr[1];
		    nextXh=xhArr[2];
		}
		//只有到了边界，才需要查询数据
		boolean pageUpFlag=false;
        boolean pageDownFlag=false;
        Long pageNumber=page.getCurrentPage();//当前页数
        Long totalPage=page.getTotalPage();//总页数
        if(preXh.equals("0") && pageNumber>1){
            //如果pageUp为0,证明当前xh已经是当前页面第一条记录，这时应该查询上一页的数据
            pageUpFlag=true;
        }else if(nextXh.equals("0") && pageNumber<=totalPage){
            //且不是最后一页
            //如果pageDown为0,证明当前页面已经走到最后一条记录了，这时应该查询下一页的数据
            pageDownFlag=true;
        }
        if(pageUpFlag || pageDownFlag){
            int locateIndex=0;//当前xh在新的查询数据中的位置
            //遇到分页的时候就多查点数据
            List<Vehicle> vehicles=YxxxglServiceImpl.queryVehicleList(
                    info,startTime,endTime,page);
            int size=vehicles.size();
            for(int i=0;i<size;i++){
                Vehicle tempVehicle=vehicles.get(i);
                String newXh=tempVehicle.getXh();
                if(currentXh.equals(newXh)){
                    locateIndex=i;
                }
                if(i==0){
                    xhs=newXh;
                }else{
                    xhs=xhs+","+newXh;
                }
            }
            if(pageUpFlag){
                //上一页
                preXh=vehicles.get(locateIndex-1).getXh();
            }else if(pageDownFlag){
                //下一页
                if(locateIndex+1<size){
                    nextXh=vehicles.get(locateIndex+1).getXh();
                }
            }
        }
		info.setXh(currentXh);
		info=YxxxglServiceImpl.findYxsqxzByxhFirstIn(info,startTime,endTime);
		transfCodeToName(info);
		mv.addObject("info",info);
		mv.addObject("preXh",preXh);
		mv.addObject("xhs",xhs);
		mv.addObject("nextXh",nextXh);
		mv.addObject("startTime",startTime);
		mv.addObject("endTime",endTime);
		mv.addObject("pageInfo",page);
		return mv;
	}*/
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView findYxsqxzByxhFirstIn(HttpServletRequest request,HttpServletResponse response,PageUtil page,
			Vehicle info,String startTime,String endTime,String lshs,String url,String applyNo){
		boolean isTypeFlag=false;
	    ModelAndView mv=null;
		String lsh=info.getLsh();
		String preLsh="";//上一个序号
		String currentLsh="";//当前序号
		String nextLsh="";//下一个序号
		if(StringUtils.isNotEmpty(lsh)){
		    String[] lshArr=lsh.split(",");
		    preLsh=lshArr[0];
		    currentLsh=lshArr[1];
		    nextLsh=lshArr[2];
		}
		//只有到了边界，才需要查询数据
		/*boolean pageUpFlag=false;
        boolean pageDownFlag=false;
        Long pageNumber=page.getCurrentPage();//当前页数
        Long totalPage=page.getTotalPage();//总页数
        if(preXh.equals("0") && pageNumber>1){
            //如果pageUp为0,证明当前xh已经是当前页面第一条记录，这时应该查询上一页的数据
            pageUpFlag=true;
        }else if(nextXh.equals("0") && pageNumber<=totalPage){
            //且不是最后一页
            //如果pageDown为0,证明当前页面已经走到最后一条记录了，这时应该查询下一页的数据
            pageDownFlag=true;
        }
        if(pageUpFlag || pageDownFlag){
            int locateIndex=0;//当前xh在新的查询数据中的位置
            //遇到分页的时候就多查点数据
            List<Vehicle> vehicles=YxxxServiceImpl.queryVehicleList(
                    info,startTime,endTime,page);
            int size=vehicles.size();
            for(int i=0;i<size;i++){
                Vehicle tempVehicle=vehicles.get(i);
                String newXh=tempVehicle.getXh();
                if(currentXh.equals(newXh)){
                    locateIndex=i;
                }
                if(i==0){
                    xhs=newXh;
                }else{
                    xhs=xhs+","+newXh;
                }
            }
            if(pageUpFlag){
                //上一页
                preXh=vehicles.get(locateIndex-1).getXh();
            }else if(pageDownFlag){
                //下一页
                if(locateIndex+1<size){
                    nextXh=vehicles.get(locateIndex+1).getXh();
                }
            }
        }*/
		info.setLsh(currentLsh);
		Sys_Role sysRole=(Sys_Role)request.getSession().getAttribute("role");
		info =YxxxglServiceImpl.findYxxxglByxh(info,startTime,endTime,sysRole);
		//info=YxxxServiceImpl.findYxshByxhFirstIn(info,startTime,endTime);
		Document doc=null;
		try {
			doc = DocumentHelper.parseText(info.getTpurl()==null?"":info.getTpurl());
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		List<Vehicle> listTpurl = new ArrayList<Vehicle>(); //存放图片列表对象
		Map<Integer,Integer> map = new HashMap<Integer,Integer>();
		
		if(info.getYwlx()!=null && info.getYwyy()!=null){
		    int registerNum=11;             		 //注册--A
		    int transformNum = 6 ; //转移 B
		    int changeNum =5;  //变更和补换领  --D、K、L
		    int mortgageNum=7;             		 //抵押和解除抵押 --E
		    int logoutNum=4;					//注销--G
		    int changeIntoNum=5;				//转入--I
		    int suodingNum=3;
		    if(info.getYwlx().equals("A")){
				for(int i=0;i<registerNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }else if(info.getYwlx().equals("B")){
		    	for(int i=0;i<transformNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }else if(info.getYwlx().equals("D") || info.getYwlx().equals("K") || info.getYwlx().equals("L")){
		    	for(int i=0;i<changeNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }else if(info.getYwlx().equals("E")){
		    	for(int i=0;i<mortgageNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }else if(info.getYwlx().equals("G")){
		    	for(int i=0;i<logoutNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }else if(info.getYwlx().equals("I")){
		    	for(int i=0;i<changeIntoNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }else if(info.getYwlx().equals("S")){
		    	for(int i=0;i<suodingNum;i++){ //初始化不同业务下各档案类型
					map.put(i, 0);
				}
		    }
	
			map.put(100, 0); //初始化一个全部档案id，用于累加所有档案
			
			if(null!=doc){
				Element root = doc.getRootElement();
				List nodes = root.elements();
				for (Iterator<?> it = nodes.iterator(); it.hasNext();) {
					Vehicle obj =new Vehicle();
					Element e = (Element) it.next();
					String key = e.attributeValue("id");
					obj.setId(key);
					try {
						obj.setSingleIpaddress(toHexString(encrypt(e.getStringValue(), "ahhwxxjs")).toUpperCase());
					} catch (Exception e1) {
						e1.printStackTrace();
					}
									
					listTpurl.add(obj);			
				}
				for(Entry<Integer, Integer> mapTemp : map.entrySet()){
					for(Vehicle list : listTpurl){
						if(mapTemp.getKey().toString().equals(list.getId())){
							map.put(mapTemp.getKey(), mapTemp.getValue().intValue()+1);
						}
						if(mapTemp.getKey().toString().equals("100")){
							map.put(mapTemp.getKey(), mapTemp.getValue().intValue()+1);
						}
						/*if(list.getId().equals("0")){
							isTypeFlag=true;
						}*/					
					}
				}
			}
		}else{
			Element root = doc.getRootElement();
			List nodes = root.elements();
			for (Iterator<?> it = nodes.iterator(); it.hasNext();) {
				Vehicle obj =new Vehicle();
				Element e = (Element) it.next();
				String key = e.attributeValue("id");
				obj.setId(key);
				try {
					obj.setSingleIpaddress(toHexString(encrypt(e.getStringValue(), "ahhwxxjs")).toUpperCase());
				} catch (Exception e1) {
					e1.printStackTrace();
				}
								
				listTpurl.add(obj);
			}
			isTypeFlag=true;
		}
			if(StringUtils.isNotEmpty(url)){
				//mv = new ModelAndView("yxsh/jdcViewFlag");
				if(isTypeFlag==true){
					 mv = new ModelAndView("yxsh/vehicle/jdcView");
				}else{
					 mv = new ModelAndView("yxsh/vehicle/jdcViewFlag");
				}
			}else{
				//mv = new ModelAndView("yxgl/jdcViewFlag");
				if(isTypeFlag==true){
					 mv = new ModelAndView("yxgl/jdcView");
				}else{
					 mv = new ModelAndView("yxgl/jdcViewFlag");
				}
			}

		mv.addObject("tpNums", map);
		mv.addObject("listTpurl",listTpurl);
		mv.addObject("info",info);
		mv.addObject("preLsh",preLsh);
		mv.addObject("lshs",lshs);
		mv.addObject("applyNo",applyNo);
		mv.addObject("nextLsh",nextLsh);
		mv.addObject("startTime",startTime);
		mv.addObject("endTime",endTime);
		mv.addObject("pageInfo",page);
		return mv;
	}
	
	
	/**
	 * 根据过车辆序号查询影像申请档案详情，控制翻页
	 * @param request
	 * @param response
	 * @param info
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void findYxsqxzByxhUpAndDown(HttpServletRequest request,HttpServletResponse response,GcPage<Vehicle> pages,
			Vehicle info,String startTime,String endTime){
		 GcPage<Vehicle> page=YxxxglServiceImpl.findYxsqxzByxhUpAndDown(pages,info,startTime,endTime);
		ControllerUtil.renderJson(response, page, "encoding:UTF-8", "no-cache:false");
	}
	/**
	 * 查询影像审核关联图片
	 * @param request
	 * @param response
	 * @param info
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void findYxxxglRelation(HttpServletRequest request,HttpServletResponse response,Vehicle info){
		 List<Vehicle> list=YxxxglServiceImpl.findYxshByxh(info);
		 for(int i=0,size=list.size();i<size;i++){
			 Vehicle tempVehicle=list.get(i);
			 String tpUrl=tempVehicle.getTpurl();
			 try {
				 String tempTpUrl=toHexString(encrypt(tpUrl, "ahhwxxjs")).toUpperCase();
				 tempVehicle.setTpurl(tempTpUrl);
			 }catch (Exception e){
				e.printStackTrace();
			 }
		 }
		ControllerUtil.renderJson(response, list, "encoding:UTF-8", "no-cache:false");
	}

	/**
	 * 单个审批
	 * @param request
	 * @param response
	 * @param info
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void updateYxxzzt(HttpServletRequest request,HttpServletResponse response,Vehicle info){
		 int flag=YxxxglServiceImpl.updateYxxzzt(info);
		 if(flag>=1){
			 ControllerUtil.renderJson(response, "true", "encoding:UTF-8", "no-cache:false");
		 }else{
			 ControllerUtil.renderJson(response, "false", "encoding:UTF-8", "no-cache:false");
		 }
	}

	/**
	 * 批量审批
	 * @param request
	 * @param response
	 * @param info
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void updateYxsqxzBatch(HttpServletRequest request,HttpServletResponse response,Vehicle info){
		 int flag=YxxxglServiceImpl.updateYxsqxzBatch(info);
		 if(flag>=1){
			 ControllerUtil.renderJson(response, "true", "encoding:UTF-8", "no-cache:false");
		 }else{
			 ControllerUtil.renderJson(response, "false", "encoding:UTF-8", "no-cache:false");
		 }
	}
	
	
	/**
	 * 跳转到影像审核下载页面
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String yxshxz(HttpServletResponse response){
		return "yxgl/yxshxz";
	}
	
	/**
	 * 分页显示影像审核下载列表
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void findYxshxzPage(HttpServletRequest request,HttpServletResponse response,
								Page<Vehicle> pages,Vehicle info,String startTime,String endTime){
		Page<Vehicle> list = YxxxglServiceImpl.findYxshxzxx(pages, info,startTime,endTime);
		ControllerUtil.renderJson(response, list, "encoding:UTF-8","no-cache:false");
	}
	
	/**
	 * 根据车辆记录首次查询影像审核档案详情，第一次进入详情
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView findYxshxzByxhFirstIn(HttpServletRequest request,HttpServletResponse response,GcPage<Vehicle> pages,
			Vehicle info,String startTime,String endTime){
		ModelAndView mv = new ModelAndView("yxgl/checkyxxzsh");
		GcPage<Vehicle> list=YxxxglServiceImpl.findYxshxzByxhFirstIn(pages,info,startTime,endTime);
		mv.addObject("list",list.getRows().get(0));
		mv.addObject("page",list);
		mv.addObject("startTime",startTime);
		mv.addObject("endTime",endTime);
		mv.addObject("hphm",info.getHphm());
		mv.addObject("hpzl",info.getHpzl());
		return mv;
	}

	/**
	 * 通过xh查询驾驶证信息
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView findJszByXh(String xh){
		ModelAndView mv = new ModelAndView("yxgl/jszView");
		Driver_audit driver_audit=YxxxglServiceImpl.findJszByxh(xh);
		mv.addObject("driver_audit",driver_audit);
		return mv;
	}

	/**
	 * 根据过车辆序号查询影像申请档案详情，控制翻页
	 * @param request
	 * @param response
	 * @param info
	 */
	@RequestMapping(method=RequestMethod.GET)
	public void findYxshxzByxhUpAndDown(HttpServletRequest request,HttpServletResponse response,GcPage<Vehicle> pages,
			Vehicle info,String startTime,String endTime){
		 GcPage<Vehicle> page=YxxxglServiceImpl.findYxshxzByxhUpAndDown(pages,info,startTime,endTime);
		ControllerUtil.renderJson(response, page, "encoding:UTF-8", "no-cache:false");
	}

	@RequestMapping(method=RequestMethod.POST)
	public void updateYxxzztBatch(HttpServletRequest request,HttpServletResponse response,Vehicle info){
		 int flag=YxxxglServiceImpl.updateYxxzztBatch(info);
		 if(flag>=1){
			 ControllerUtil.renderJson(response, "true", "encoding:UTF-8", "no-cache:false");
		 }else{
			 ControllerUtil.renderJson(response, "false", "encoding:UTF-8", "no-cache:false");
		 }
	}
	/**
	 * 申请下载页面，下载前确认是否包含未授权记录id
	 * @param request
	 * @param response
	 * @param ids
	 */
	@RequestMapping(method=RequestMethod.POST)
	public  void verifyDownloadauthority(HttpServletRequest request,HttpServletResponse response,String ids) {
		List<Vehicle> list = YxxxglServiceImpl.findYxxxByIds(ids);
		for(Vehicle ll:list){
			if(!ll.getYxxzzt().equals("2")){
			ControllerUtil.renderJson(response, "false", "encoding:UTF-8", "no-cache:false");
			return;
			}
		}
		ControllerUtil.renderJson(response, "true", "encoding:UTF-8", "no-cache:false");
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public  void findyxxxsqzt(HttpServletRequest request,HttpServletResponse response,String ids) {
		List<Vehicle> list = YxxxglServiceImpl.findyxxxsqztByIds(ids);
		for(Vehicle ll:list){
			if(ll.getYxxzzt().equals("2")){
			ControllerUtil.renderJson(response, "false", "encoding:UTF-8", "no-cache:false");
			return;
			}
		}
		ControllerUtil.renderJson(response, "true", "encoding:UTF-8", "no-cache:false");
	}
	
	/*@RequestMapping(method=RequestMethod.GET)
	@SystemLog(Modelname="影像下载申请",operationType="2",operationName="批量下载档案")
	public  void downloadPic(HttpServletRequest request,HttpServletResponse response,Vehicle info) {		
		Date date = new Date();
		SimpleDateFormat time=new SimpleDateFormat("yyyyMMddHHmmss"); 
		String nowTime=time.format(date);		
	    String ZipFileName  = "daxx_"+nowTime+".zip";
	    //设置response返回参数
        response.setHeader("Content-Type","text/html;charset=UTF-8");  
		//response.reset();
		response.setContentType("application/x-msdownload");
        response.setHeader("Content-Type", "application/octet-stream");
      //  Properties pro;
       // String ftp_path = null;
		try {
		//	pro = PropertiesLoaderUtils.loadAllProperties("application.properties");
		  //  ftp_path  = pro.getProperty("ftp_destpath");
			response.setHeader("Content-Disposition", "attachment; filename=" +new String(ZipFileName.getBytes("gb2312"), "ISO8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} 
		   String ids=request.getParameter("ids");
		    //根据前台选择id查询数据库记录
			List<Vehicle> list = YxxxglServiceImpl.findYxxxPicByIds(ids);
			
			//查出的记录打包写入服务器中，并提供下载
            ZipOutputStream zos=null;
            InputStream is =null;
            HttpClient client = HttpClientBuilder.create().build();
			try {
				 zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			//遍历文件
		    for(int i=0;i<list.size();i++){
				if(list.get(i).getTpurl()!=null){
				//String picPath=list.get(i).getTpurl().trim();
				//String str=picPath.substring(picPath.lastIndexOf("/")+1);
				String ipAddr=list.get(i).getTpurl().trim();
	            HttpGet httpget = new HttpGet(ipAddr);
	            HttpResponse res = null; 	
	           // File file = new File(ftp_path+str);
               try {
		            	res = client.execute(httpget);
		                HttpEntity entity = res.getEntity(); 
            	   		is = entity.getContent();
		               // is= new FileInputStream(file);					    
                } catch (IOException e){
                	continue;
                }
          			try {
						zos.putNextEntry(new ZipEntry(list.get(i).getTpid()+".jpg"));
						 int len=0;  
    	                    byte[] buffer = new byte[1024*1024]; 
    	                    while ((len = is.read(buffer)) != -1) {  
    	                    zos.write(buffer, 0, len); 
    	                    }
    	                    zos.closeEntry();
    	                    is.close();
					} catch (IOException e) {
						e.printStackTrace();
					} 			
               	 }
		    }
			try {
				zos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  	//更新下载状态
			for(int i=0;i<list.size();i++){
				if(list.get(i).getPic()!=null){
		
			//Gscz_T_alarm gs=new Gscz_T_alarm();
			//gs.setId(ids);
		//	int xzcs=list.get(i).getXzcs();
	//		gs.setXzcs(xzcs+1);	
				System.out.println(list.get(i).getId());		
			boolean res =wfxxservice.updatexzcs(list.get(i));
		
				}
			}
	}	*/
	@RequestMapping(method=RequestMethod.GET)
	public  void downloadSinglePic(HttpServletRequest request,HttpServletResponse response,Dagl_T_Audit dagl_T_Audit) {		
	    editAuditInfo(dagl_T_Audit,"02");
	    Date date = new Date();
		SimpleDateFormat time=new SimpleDateFormat("yyyyMMddHHmmss"); 
		String nowTime=time.format(date);		
	    String ZipFileName  = "daxx_"+nowTime+".zip";
	    //设置response返回参数
        response.setHeader("Content-Type","text/html;charset=UTF-8");  
		//response.reset();
		response.setContentType("application/x-msdownload");
        response.setHeader("Content-Type", "application/octet-stream");
        Properties pro;
        String ftp_path = null;
		try {
			pro = PropertiesLoaderUtils.loadAllProperties("application.properties");
		    ftp_path  = pro.getProperty("ftp_destpath");
			response.setHeader("Content-Disposition", "attachment; filename=" +new String(ZipFileName.getBytes("gb2312"), "ISO8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		   String lsh=request.getParameter("lsh");
		   String xh=request.getParameter("xh");
		    //根据前台选择id查询数据库记录
			Vehicle info = YxxxglServiceImpl.findYxxxPicByxh(lsh,xh);
			Document doc=null;
			try {
				doc = DocumentHelper.parseText(info.getTpurl()==null?"":info.getTpurl());
			} catch (DocumentException e1) {
				e1.printStackTrace();
			}
			List<Vehicle> listTpurl = new ArrayList<Vehicle>(); //存放图片列表对象

			if(null!=doc){
				Element root = doc.getRootElement();
				List nodes = root.elements();
				for (Iterator<?> it = nodes.iterator(); it.hasNext();) {
					Vehicle obj =new Vehicle();
					Element e = (Element) it.next();
					String key = e.attributeValue("id");
					obj.setId(key);
					obj.setSingleIpaddress(e.getStringValue());				
					listTpurl.add(obj);

				}
			}
			//查出的记录打包写入服务器中，并提供下载
            ZipOutputStream zos=null;
            InputStream is =null;
            HttpClient client = HttpClientBuilder.create().build();
			try {
				 zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			//遍历文件
		    for(int i=0;i<listTpurl.size();i++){
				if(listTpurl.get(i).getSingleIpaddress()!=null){
				String ipAddr=listTpurl.get(i).getSingleIpaddress().trim();
				String tpName=listTpurl.get(i).getSingleIpaddress().trim().substring(listTpurl.get(i).getSingleIpaddress().trim().lastIndexOf("/")+1);
	            HttpGet httpget = new HttpGet(ipAddr);  
	            HttpResponse res = null; 	
               try {
		            	res = client.execute(httpget);
		                HttpEntity entity = res.getEntity(); 
            	   		is = entity.getContent();
                } catch (IOException e){
                	continue;
                }
          			try {
						zos.putNextEntry(new ZipEntry(tpName));
						 int len=0;  
    	                    byte[] buffer = new byte[1024*1024]; 
    	                    while ((len = is.read(buffer)) != -1) {  
    	                    zos.write(buffer, 0, len); 
    	                    }
    	                    zos.closeEntry();
    	                    is.close();
					} catch (IOException e) {
						e.printStackTrace();
					} 			
               	 }
		    }
			try {
				zos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	//operatType 操作类型  01:打印  02:下载  
	public void editAuditInfo(Dagl_T_Audit dagl_T_Audit,String operatType){
	    //先查询目前下载次数
	    Dagl_T_Audit tempAudit=auditService.queryAuditByApplyNo(dagl_T_Audit);
	    if("02".equals(operatType)){
	        int tempNum=tempAudit.getDownloadNum();
	        tempNum=tempNum+1;
	        dagl_T_Audit.setDownloadNum(tempNum);
	    }else if("01".equals(operatType)){
	        int tempNum=tempAudit.getPrintNum();
            tempNum=tempNum+1;
            dagl_T_Audit.setPrintNum(tempNum);
	    }
	   
	    auditService.editAudit(dagl_T_Audit);
	}
	
	/**
     *统计打印次数
     * @param request
     * @param response
     * @param ids
     */
    @RequestMapping(method=RequestMethod.POST)
    public  void countPrintNum(HttpServletRequest request,HttpServletResponse response,Dagl_T_Audit dagl_T_Audit) {
        editAuditInfo(dagl_T_Audit,"01");
    }
    
    /**
     * @param request
     * @param response
     */
    private static Configuration freemarkerConfig;  
    
    static {  
        freemarkerConfig = new Configuration(Configuration.VERSION_2_3_26);  
        freemarkerConfig.setEncoding(Locale.getDefault(), "UTF-8");  
    } 
    
    @RequestMapping(method=RequestMethod.GET)
    public  void downloadWordF(HttpServletRequest request,HttpServletResponse response,String startTime,String endTime,String hphm,String hpzl)
    		throws IOException, TemplateException {
	    	response.setCharacterEncoding("utf-8");
	        response.setContentType("application/msword");
	        // 设置浏览器以下载的方式处理该文件
			SimpleDateFormat time=new SimpleDateFormat("yyyyMMddHHmmss");
			String nowTime=time.format(new Date());
		    String FileName  = "dagl_"+nowTime+".doc";
	        response.addHeader("Content-Disposition", "attachment;filename="+new String(FileName.getBytes("gb2312"), "ISO8859-1"));
    	 	List<Vehicle> list = YxxxglServiceImpl.getvehicleList(startTime,endTime,hphm,hpzl);
	        Map<String,Object> result = new HashMap<String,Object>();
	        for (Vehicle temp : list){
	        	if(temp.getDabh()==null){
	        		temp.setDabh(" ");
	        	}
	        }
	        result.put("vehList", list);
	        int i =43;//word一页行数
	        List<String> listNum = new ArrayList<String>();
	        //result.put("rownum", list.size()%i +2);
	        int k = i - list.size()%i-4;
	        for(int j =0;j<k;j++){
	        	listNum.add("<w:p></w:p>");
	        }
	        result.put("rownum", listNum);
			freemarkerConfig.setTemplateLoader(new URLTemplateLoader() {
	            @Override
	            protected URL getURL(String arg0) {
	            	//this.getClass().getResource("/").getPath()
	            	//System.out.println(this.getClass().getResource("/").getPath());
	            	//System.out.println(YxxxglServiceImpl.class.getResource("/").getPath()+"template1.xml");
	                return YxxxglServiceImpl.class.getResource("/template/template2003.ftl");//此处需要注意test.xml模板的路径,不要搞错了，否则获取不到模板，我是放在src/main/java目录下  
	            }  
	        });
	        Writer outputstream= new  OutputStreamWriter(response.getOutputStream()); //定义out，把远程文件流写入其中
	        Template temp = freemarkerConfig.getTemplate("template2003.ftl");
	          
	       // File targetFile = new File(filePath);
	      //  Writer out = new OutputStreamWriter(new FileOutputStream(targetFile),"UTF-8");  
	          
	        //执行模板替换  
	        temp.process(result, outputstream);
	        outputstream.flush();
	        outputstream.close();
    }
    /**
     *统计word中需下载记录数
     * @param request
     * @param response
     * @param ids
     */
    @RequestMapping(method=RequestMethod.POST)
    public  void downloadVehCount(HttpServletRequest request,HttpServletResponse response,String startTime,String endTime,String hphm,String hpzl) {
    	int i = YxxxglServiceImpl.countVehice(startTime,endTime,hphm,hpzl);
    	ControllerUtil.renderJson(response, i, "encoding:UTF-8", "no-cache:false");
    }
	/**
	 * 分页查询机动车档案列表(档案移交下载功能)
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void findvehicledayjPage(HttpServletRequest request,HttpServletResponse response,
								Page<Vehicle> pages,Vehicle info,String startTime,String endTime){
		HttpSession session=request.getSession();
		if(null!=session){
			Sys_User sysUser=(Sys_User)session.getAttribute("user");
			String yhdh=sysUser.getYhdh();
			info.setCjr(yhdh);
		}
		Page<Vehicle> list = YxxxglServiceImpl.findvehicledayjPage(pages, info,startTime,endTime);
		ControllerUtil.renderJson(response, list, "encoding:UTF-8","no-cache:false");
	}
}
